package cn.amaake.magicplugin.nacos.autoconfigure;

import cn.amaake.magicplugin.nacos.config.NacosConfig;
import cn.amaake.magicplugin.nacos.util.ConfigParserUtils;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;

import java.util.Properties;


public class NacosConfigEnvironmentProcessor implements EnvironmentPostProcessor, Ordered {

    private final Logger logger = LoggerFactory.getLogger(NacosConfigEnvironmentProcessor.class);
    private NacosConfig nacosConfigProperties;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        nacosConfigProperties = new NacosConfig();
        nacosConfigProperties.setEnableConfig(environment.getProperty("magic-api.nacos.enable-config", Boolean.class));
        nacosConfigProperties.setEnableStartConfig(environment.getProperty("magic-api.nacos.enable-start-config", Boolean.class));
        nacosConfigProperties.setServerAddr(environment.getProperty("magic-api.nacos.server-addr", String.class));
        nacosConfigProperties.setDataId(environment.getProperty("magic-api.nacos.data-id", String.class));
        nacosConfigProperties.setGroup(environment.getProperty("magic-api.nacos.group", String.class));
        nacosConfigProperties.setEnabledAuth(environment.getProperty("magic-api.nacos.enabled-auth", Boolean.class, false));
        nacosConfigProperties.setUsername(environment.getProperty("magic-api.nacos.username", String.class));
        nacosConfigProperties.setPassword(environment.getProperty("magic-api.nacos.password", String.class));
        nacosConfigProperties.setNamespace(environment.getProperty("magic-api.nacos.namespace", String.class,""));
        nacosConfigProperties.setTimeout(environment.getProperty("magic-api.nacos.timeout", Integer.class, 3000));
        nacosConfigProperties.setType(environment.getProperty("magic-api.nacos.type", ConfigType.class, ConfigType.YAML));

        if(nacosConfigProperties.isEnableStartConfig()) {
            try {
                Properties properties = new Properties();
                properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosConfigProperties.getServerAddr());
                if (nacosConfigProperties.isEnabledAuth()){
                    properties.setProperty(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername());
                    properties.setProperty(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword());
                }
                if(StrUtil.isNotEmpty(nacosConfigProperties.getNamespace())){
                    properties.setProperty(PropertyKeyConst.NAMESPACE, nacosConfigProperties.getNamespace());
                }
                ConfigService configService = NacosFactory.createConfigService(properties);
                String content = configService.getConfig(nacosConfigProperties.getDataId(), nacosConfigProperties.getGroup(), nacosConfigProperties.getTimeout());
                Properties dataproperties = ConfigParserUtils.parse(content,nacosConfigProperties.getType());
                PropertySource<?> propertySource = new PropertiesPropertySource("nacos-center-config", dataproperties);
                environment.getPropertySources().addLast(propertySource);
            } catch (NacosException e) {
                throw new RuntimeException("加载Nacos配置失败",e);
            }
        }
    }

    // Do not set the minimum priority for future expansion needs

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 5;
    }


}
